package com.code.complex;

import java.util.Timer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class FibonacciSeqTimeComplex {

  /**
   * 递归获取第n个斐波拉切数
   * @param n
   * @return
   */
  public static int recursionFib(int n){

    if (n <= 1) {
      return n;
    }

    return recursionFib(n - 1) + recursionFib(n - 2);
  }

  /**
   * 循环获取第n个斐波拉切数
   * @param n
   * @return
   */
  public static int forLoopFin(int n) {
    if (n <=1){
      return n;
    }

    int first = 0;
    int second = 1;

    int tmp;
    for (int i = 0; i < n - 1 ; i++) {

      tmp = first + second;
      first = second;
      second = tmp;
    }

    return second;
  }

  public static void main(String[] args) throws Exception{

    int n = 48;


    CountDownLatch countDownLatch = new CountDownLatch(2);

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), 10, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));

    threadPoolExecutor.execute(()->{

      System.out.println("recursion fib finish  " + n + " 位斐波那切数: " +recursionFib(n));
      countDownLatch.countDown();
    });

    threadPoolExecutor.execute(()->{

      System.out.println("forLoopFin fib finish  " + n + " 位斐波那切数: " +forLoopFin(n));
      countDownLatch.countDown();
    });

    // 等待countdown数结束
    countDownLatch.await();

    //记得使用完成关闭线程
    threadPoolExecutor.shutdown();
  }
}
